package controller

import (
	"github.com/gin-gonic/gin"
	"go-shop-demo/app/common"
	"go-shop-demo/app/consts"
	"go-shop-demo/app/dto"
	"go-shop-demo/app/model"
	"go-shop-demo/app/service"
	"log"
	"net/http"
)

func AddGoodser(c *gin.Context) {
	goodsDto := dto.AddGoodsDto{}
	c.ShouldBindJSON(&goodsDto)
	if len(goodsDto.GoodsName) == 0 || goodsDto.Price == 0 {
		c.JSON(400, gin.H{"msg": "货物名称未填写或价格不能为0"})
		return
	}
	goods := model.Goods{GoodsName: goodsDto.GoodsName, Price: goodsDto.Price}
	err := service.AddGoods(goods)
	if err != nil {
		log.Printf("err:%v", err)
		c.JSON(500, gin.H{"msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"msg": "添加货物成功"})
	return
}

func DeleteGoods(c *gin.Context) {
	req := common.DeleteReq{}
	err := c.ShouldBindJSON(&req)
	common.CheckErr(err, consts.ClientError, "")
	service.DeleteGoods(req.ID)
	c.JSON(http.StatusOK, gin.H{"msg": "删除货物成功"})
	return
}

func GetGoods(c *gin.Context) {
	p := common.Pageable{}
	err := c.ShouldBind(&p)
	common.CheckErr(err, consts.ClientError, "")
	total, goods := service.GetGoods(p.Page, p.Size)
	res := dto.NewGoodsPageDto(goods)
	data := common.GetPageResult(res, p.Page, p.Size, total)
	c.JSON(http.StatusOK, common.GetDataResponse(data))
	return
}

func GetSingleGoods(c *gin.Context) {
	g := dto.SingleGoods{}
	err := c.ShouldBind(&g)
	common.CheckErr(err, consts.ClientError, "")
	goods := service.GetSingleGoods(g.GoodsName)
	c.JSON(http.StatusOK, common.GetDataResponse(goods))
	return
}
